import { Inject, Controller, Get, Logger } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { UserService } from '../service/user.service';
import { ILogger } from '@midwayjs/logger';
import { AnalyticsService } from '../service/analytics.service';

@Controller('/api')
export class APIController {
  @Inject()
  ctx: Context;

  @Inject()
  userService: UserService;

  @Inject()
  analyticsService: AnalyticsService;

  @Logger()
  logger: ILogger;

  /**
   * 获取用户信息接口（需要认证）
   */
  @Get('/userinfo')
  async getUserInfo() {
    // 从上下文中获取用户信息
    const user = this.ctx.state.user;
    
    this.logger.info(`[APIController] 获取用户信息请求: 用户ID ${user?.id}`);
    
    if (!user) {
      this.logger.warn('[APIController] 获取用户信息失败: 未认证');
      return {
        code: 401,
        message: '未认证',
        data: null
      };
    }

    // 埋点：记录API访问事件
    await this.analyticsService.trackAPIAccess(user.id, '/api/userinfo', 'GET');
    
    this.logger.info(`[APIController] 获取用户信息成功: 用户ID ${user.id}`);
    return {
      code: 200,
      message: '获取成功',
      data: user
    };
  }

  /**
   * 获取所有用户接口（需要认证，仅用于演示）
   */
  @Get('/users')
  async getUsers() {
    // 从上下文中获取用户信息
    const currentUser = this.ctx.state.user;
    
    this.logger.info(`[APIController] 获取所有用户请求: 当前用户ID ${currentUser?.id}`);
    
    if (!currentUser) {
      this.logger.warn('[APIController] 获取所有用户失败: 未认证');
      return {
        code: 401,
        message: '未认证',
        data: null
      };
    }

    const users = await this.userService.getAllUsers();
    
    // 埋点：记录API访问事件
    await this.analyticsService.trackAPIAccess(currentUser.id, '/api/users', 'GET');
    
    this.logger.info(`[APIController] 获取所有用户成功: 共${users.length}个用户`);
    return {
      code: 200,
      message: '获取成功',
      data: users
    };
  }
}